package cn.xiaoya.boot.jpa.config;

import cn.xiaoya.boot.jpa.constants.DbConstants;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;
import java.util.Objects;

/**
 * @author xieya
 * @date 2021/7/26
 */
@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = DbConstants.ENTITY_MANAGER_FACTORY_ORDERS,
        transactionManagerRef = DbConstants.TX_MANAGER_ORDERS,
        basePackages = {"cn.xiaoya.boot.jpa.repository.orders"})
public class JpaOrdersConfig {
    @Resource(name = "hibernateVendorProperties")
    private Map<String, Object> hibernateVendorProperties;

    /**
     * Primary // 需要特殊添加，否则初始化会有问题
     * 创建 orders 数据源
     */
    @Bean(name = "ordersDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.orders")
    @Primary
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 创建 LocalContainerEntityManagerFactoryBean
     */
    @Bean(name = DbConstants.ENTITY_MANAGER_FACTORY_ORDERS)
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                // 数据源
                .dataSource(this.dataSource())
                // 获取并注入 Hibernate Vendor 相关配置
                .properties(hibernateVendorProperties)
                // 数据库实体 entity 所在包
                .packages("cn.xiaoya.boot.jpa.dataobject")
                // 设置持久单元的名字，需要唯一
                .persistenceUnit("ordersPersistenceUnit")
                .build();
    }

    /**
     * 创建 PlatformTransactionManager
     */
    @Bean(name = DbConstants.TX_MANAGER_ORDERS)
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(Objects.requireNonNull(entityManagerFactory(builder).getObject()));
    }
}
